package com.res.simulator.handler;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.res.common.handler.CommonHandler;
import com.res.simulator.transformer.RestServiceTransformer;
import com.res.simulator.view.ResultView;
import com.res.simulator.model.RestServiceModel;
import com.res.simulator.plugins.MessageCommunicationClientPlugin;
import com.res.system.utils.SimulatorUtilities;
import com.res.system.utils.SimulatorUtilities.ConfigData;
import com.sip.comserver.communication.CommunicationMessage;
import com.sip.dbadapter.dao.domain.ScanTypeRest;

public class RestServiceHandler implements CommonHandler<List<ResultView>, RestServiceModel> {

    private static final Logger logger = Logger.getLogger(RestServiceHandler.class);


    public List<ResultView> process(RestServiceModel model) throws Exception {

        // TODO Auto-generated method stub
        RestServiceTransformer restTransformer = new RestServiceTransformer();
        // this apiObj type should be changed
        ScanTypeRest scanTypeRest = restTransformer.transformModelToDomian(model);
        String message = commit(scanTypeRest);
        restTransformer.transformDomianToView(scanTypeRest);
        ResultView restView = new ResultView();
        restView.setResult(message);
        restView.setApiName("test");
        restView.setInputParams(model.getContent());
        List<ResultView> resultViewList = new ArrayList<ResultView>();
        resultViewList.add(restView);
        return resultViewList;
    }

    private String commit(ScanTypeRest scanType) throws Exception {

        final CommunicationMessage message = new CommunicationMessage();

        final String serverAddress = SimulatorUtilities.getConfigData(ConfigData.SERVER_ADDRESS);
        final String port = SimulatorUtilities.getConfigData(ConfigData.SERVER_PORT);

        logger.info("Message Header==>" + "JOBType:cm" + "|ID:" + serverAddress + "|Port:" + port + "|Executor:ServiceExecutorREST");

        message.setMessageHeader("JOBType:APISubmitCall|Executor:ServiceExecutorREST|ID:" + serverAddress + "|Port:" + port);

        message.setObject(scanType);

        final MessageCommunicationClientPlugin plugin = new MessageCommunicationClientPlugin();
        final CommunicationMessage returnedMessage = plugin.invoke(message);
        String methodUrl = (String) returnedMessage.getObject();
        return methodUrl;

    }

}
